<template>
    <div>
        <van-nav-bar title="收货地址" left-text="返回" left-arrow @click-left="onClickLeft" />
    </div>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field v-model="username" name="username" label="收货人" placeholder="收货人"
                :rules="[{ required: true, message: '请填写用户名' }]" />
            <van-field v-model="userphone" type="text" name="tel" label="手机号" placeholder="手机号"
                :rules="[{ required: true, message: '请填写手机号' }]" />


            <van-field v-model="fieldValue" is-link readonly label="地区" placeholder="请选择所在地区" @click="show = true" />
            <van-popup v-model:show="show" round position="bottom">
                <van-cascader v-model="cascaderValue" title="请选择所在地区" :options="options" @close="show = false"
                    @finish="onFinish" />
            </van-popup>
            <van-field v-model="useraddress" name="xiangqing" label="详情地址" placeholder="详情地址" />
        </van-cell-group>
        <div style="margin: 16rem;">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useCascaderAreaData } from '@vant/area-data';
import { adduseraddress } from '@/api/index'
import { showToast } from 'vant';
import { useStore } from 'vuex';
let store = useStore()
const show = ref(false);
const fieldValue = ref('');
const cascaderValue = ref('');
const options = useCascaderAreaData();
const onFinish = ({ selectedOptions}:any) => {
    show.value = false;
    fieldValue.value = selectedOptions.map((option: any) => option.text).join('/');

};
const username = ref('');
const userphone = ref('');
const useraddress = ref('');
const onSubmit = (values: any) => {

    values.xiangqing = fieldValue.value + ',' + values.xiangqing
    let phonetest = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
    if (values.username.length > 1 && phonetest.test(values.tel) && values.xiangqing.length > 0) {
        adduseraddress(values.username, values.xiangqing, values.tel, values.isDefault = 'false', store.state.userData[0].id).then((result: any) => {
            showToast('添加成功')
            username.value = ''
            userphone.value = ''
            useraddress.value = ''
            fieldValue.value = ''
        }).catch((err: any) => {
            showToast('网络错误')
        });

    } else {
        showToast('格式有误哦！')
    }
};


const onClickLeft = () => history.back();
</script>

<style lang="less"  scoped>

.van-nav-bar .van-icon{
    color: #333333;
}
.van-nav-bar__text{
    color: #333333;
}
</style>